// 卫生检查管理相关功能
const HygieneManager = {
    // 加载宿舍楼选择框
    async loadBuildingSelect() {
        Debug.log('加载宿舍楼选择框');
        loading.show();
        try {
            const buildings = await API.buildings.getAll();
            const buildingSelect = document.getElementById('hygieneBuilding');
            
            if (!buildings || buildings.length === 0) {
                buildingSelect.innerHTML = '<option value="">暂无宿舍楼</option>';
                document.getElementById('hygieneList').innerHTML = `
                    <div class="empty-state">
                        <p>请先添加宿舍楼</p>
                        <button class="btn btn-primary" onclick="showSection('buildings')">
                            <i class="icon building-icon"></i>去添加宿舍楼
                        </button>
                    </div>
                `;
                return;
            }

            buildingSelect.innerHTML = `
                <option value="">选择宿舍楼</option>
                ${buildings.map(building => `
                    <option value="${building.id}">${building.buildingName}</option>
                `).join('')}
            `;

            // 显示所有宿舍楼的卫生概况
            this.showBuildingOverview(buildings);
        } catch (error) {
            Debug.error('加载宿舍楼列表失败:', error);
            alert('加载宿舍楼列表失败: ' + error.message);
        } finally {
            loading.hide();
        }
    },

    // 显示宿舍楼卫生概况
    async showBuildingOverview(buildings) {
        Debug.log('显示宿舍楼卫生概况:', buildings);
        const hygieneList = document.getElementById('hygieneList');
        if (!hygieneList) {
            Debug.error('找不到hygieneList元素');
            return;
        }

        try {
            hygieneList.innerHTML = `
                <div class="building-overview">
                    <div class="building-overview-content">
                        <div class="overview-header">
                            <h3>卫生检查概览</h3>
                            <p class="overview-subtitle">选择一个宿舍楼查看详细检查记录</p>
                        </div>
                        <div class="building-cards">
                            ${buildings.map(building => `
                                <div class="building-card" onclick="HygieneManager.showBuildingDetails(${building.id})">
                                    <div class="building-card-header">
                                        <h4>${building.buildingName}</h4>
                                        <span class="hygiene-score ${this.getScoreClass(building.averageScore)}">
                                            ${building.averageScore ? building.averageScore.toFixed(1) : '--'}
                                        </span>
                                    </div>
                                    <div class="building-card-content">
                                        <div class="building-stats">
                                            <div class="stat-item">
                                                <span class="stat-label">总房间数</span>
                                                <span class="stat-value">${building.totalRooms || 0}</span>
                                            </div>
                                            <div class="stat-item">
                                                <span class="stat-label">已检查</span>
                                                <span class="stat-value">${building.checkedRooms || 0}</span>
                                            </div>
                                        </div>
                                        <div class="building-description">
                                            最近检查: ${building.lastCheckTime ? 
                                                new Date(building.lastCheckTime).toLocaleString() : 
                                                '暂无检查记录'}
                                        </div>
                                    </div>
                                    <div class="building-card-footer">
                                        <span class="view-rooms">
                                            查看检查记录 <i class="icon hygiene-icon"></i>
                                        </span>
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                </div>
            `;
            Debug.log('卫生概况渲染完成');
        } catch (error) {
            Debug.error('渲染卫生概况失败:', error);
            hygieneList.innerHTML = `
                <div class="error-state">
                    <p>加载失败: ${error.message}</p>
                    <button class="btn btn-primary" onclick="HygieneManager.loadBuildingSelect()">重试</button>
                </div>
            `;
        }
    },

    // 获取分数对应的样式类
    getScoreClass(score) {
        if (!score) return '';
        if (score >= 90) return 'score-excellent';
        if (score >= 80) return 'score-good';
        if (score >= 60) return 'score-fair';
        return 'score-poor';
    },

    // 显示添加表单
    showAddForm(roomId) {
        const form = document.getElementById('addHygieneForm');
        form.reset();
        document.getElementById('hygieneFormRoomId').value = roomId;
        showModal('addHygieneModal');
    },

    // 显示宿舍楼详细卫生记录
    async showBuildingDetails(buildingId) {
        Debug.log('显示宿舍楼详细卫生记录:', buildingId);
        loading.show();
        try {
            // 更新选择框的值
            const buildingSelect = document.getElementById('hygieneBuilding');
            buildingSelect.value = buildingId;

            // 获取该宿舍楼的所有房间
            const rooms = await API.rooms.getByBuilding(buildingId);
            const hygieneList = document.getElementById('hygieneList');

            if (!Array.isArray(rooms) || rooms.length === 0) {
                hygieneList.innerHTML = `
                    <div class="empty-state">
                        <p>该宿舍楼暂无房间</p>
                    </div>
                `;
                return;
            }

            // 获取每个房间的卫生记录
            const roomsWithRecords = await Promise.all(rooms.map(async room => {
                try {
                    const records = await API.hygiene.getByRoom(room.id);
                    return {
                        ...room,
                        hygieneRecords: Array.isArray(records) ? records : []
                    };
                } catch (error) {
                    Debug.error(`获取房间${room.id}的卫生记录失败:`, error);
                    return {
                        ...room,
                        hygieneRecords: []
                    };
                }
            }));

            hygieneList.innerHTML = `
                <div class="hygiene-room-grid">
                    ${roomsWithRecords.map(room => `
                        <div class="hygiene-room-card">
                            <div class="hygiene-room-header">
                                <h4>${room.roomNumber}</h4>
                                <span class="hygiene-score ${this.getScoreClass(this.calculateAverageScore(room.hygieneRecords))}">
                                    ${this.calculateAverageScore(room.hygieneRecords)?.toFixed(1) || '--'}
                                </span>
                            </div>
                            <div class="hygiene-room-content">
                                <div class="hygiene-stats">
                                    <div class="stat-item">
                                        <span class="stat-label">检查次数</span>
                                        <span class="stat-value">${Array.isArray(room.hygieneRecords) ? room.hygieneRecords.length : 0}</span>
                                    </div>
                                    <div class="stat-item">
                                        <span class="stat-label">最近检查</span>
                                        <span class="stat-value">
                                            ${Array.isArray(room.hygieneRecords) && room.hygieneRecords[0]?.checkTime ? 
                                                new Date(room.hygieneRecords[0].checkTime).toLocaleDateString() : 
                                                '暂无'}
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div class="hygiene-room-footer">
                                <button class="btn btn-primary" onclick="HygieneManager.showAddForm(${room.id})">
                                    <i class="icon add-icon"></i>添加记录
                                </button>
                                <button class="btn btn-secondary" onclick="HygieneManager.showRecords(${room.id})">
                                    查看记录
                                </button>
                            </div>
                        </div>
                    `).join('')}
                </div>
            `;
        } catch (error) {
            Debug.error('加载宿舍楼卫生记录失败:', error);
            alert('加载宿舍楼卫生记录失败: ' + error.message);
        } finally {
            loading.hide();
        }
    },

    // 计算平均分
    calculateAverageScore(records) {
        if (!Array.isArray(records) || records.length === 0) {
            return null;
        }
        
        try {
            Debug.log('计算平均分, 记录数:', records.length);
            const validRecords = records.filter(record => record && typeof record.score === 'number');
            if (validRecords.length === 0) {
                Debug.log('没有有效的分数记录');
                return null;
            }
            
            const sum = validRecords.reduce((acc, record) => acc + record.score, 0);
            const average = sum / validRecords.length;
            Debug.log('计算得到的平均分:', average);
            return average;
        } catch (error) {
            Debug.error('计算平均分失败:', error);
            return null;
        }
    },

    // 显示房间卫生记录
    async showRecords(roomId) {
        const modal = document.createElement('div');
        modal.className = 'modal active';
        modal.innerHTML = `
            <div class="modal-content">
                <button type="button" class="modal-close" onclick="this.closest('.modal').remove()"></button>
                <h3>卫生检查记录</h3>
                <div id="roomHygieneList"></div>
                <div class="modal-footer">
                    <button class="btn btn-primary" onclick="HygieneManager.showAddForm(${roomId})">
                        <i class="icon add-icon"></i>添加记录
                    </button>
                </div>
            </div>
        `;
        document.body.appendChild(modal);

        try {
            loading.show();
            Debug.log('加载房间卫生记录:', roomId);
            const records = await API.hygiene.getByRoom(roomId);
            Debug.log('获取到的卫生记录:', records);
            const hygieneList = document.getElementById('roomHygieneList');
            
            if (!Array.isArray(records) || records.length === 0) {
                hygieneList.innerHTML = `
                    <div class="empty-state">
                        <p>暂无卫生检查记录</p>
                    </div>
                `;
                return;
            }

            hygieneList.innerHTML = records.map(record => `
                <div class="list-item">
                    <div class="hygiene-info">
                        <h4>检查时间：${new Date(record.checkTime).toLocaleString()}</h4>
                        <p>评分：${record.score}分</p>
                        <p>备注：${record.comments || '无'}</p>
                    </div>
                    <button class="btn btn-danger" onclick="HygieneManager.delete(${record.id})">
                        <i class="icon delete-icon"></i>删除
                    </button>
                </div>
            `).join('');
        } catch (error) {
            Debug.error('加载卫生记录失败:', error);
            document.getElementById('roomHygieneList').innerHTML = `
                <div class="error-state">
                    <p>加载失败: ${error.message}</p>
                    <button class="btn btn-primary" onclick="HygieneManager.showRecords(${roomId})">重试</button>
                </div>
            `;
        } finally {
            loading.hide();
        }
    },

    // 删除卫生检查记录
    async delete(id) {
        if (!confirm('确定要删除这条卫生检查记录吗？删除后将无法恢复。')) {
            return;
        }

        try {
            loading.show();
            Debug.log('开始删除卫生检查记录:', id);
            await API.hygiene.delete(id);
            Debug.log('卫生检查记录删除成功');
            
            // 重新加载数据
            const buildingId = document.getElementById('hygieneBuilding').value;
            if (buildingId) {
                await this.showBuildingDetails(buildingId);
            } else {
                await this.loadBuildingSelect();
            }
            
            // 关闭模态框
            const modal = document.querySelector('.modal.active');
            if (modal) {
                modal.remove();
            }
        } catch (error) {
            Debug.error('删除卫生检查记录失败:', error);
            alert('删除卫生检查记录失败: ' + (error.message || '未知错误'));
        } finally {
            loading.hide();
        }
    },

    // 初始化
    init() {
        this.loadBuildingSelect();
        
        // 监听宿舍楼选择变化
        document.getElementById('hygieneBuilding').addEventListener('change', (e) => {
            const buildingId = e.target.value;
            if (buildingId) {
                this.showBuildingDetails(buildingId);
            } else {
                this.loadBuildingSelect();
            }
        });

        // 添加表单提交处理
        document.getElementById('addHygieneForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            const roomId = parseInt(formData.get('roomId'));
            const record = {
                roomId: roomId,
                score: parseInt(formData.get('score')),
                comments: formData.get('comments'),
                checkTime: new Date().toISOString()
            };

            try {
                loading.show();
                Debug.log('添加卫生检查记录:', record);
                await API.hygiene.create(record);
                hideModal('addHygieneModal');
                
                // 获取当前选中的宿舍楼ID
                const buildingId = document.getElementById('hygieneBuilding').value;
                
                // 如果在模态框中，先关闭模态框
                const modal = document.querySelector('.modal.active');
                if (modal) {
                    modal.remove();
                }
                
                // 重新加载数据
                if (buildingId) {
                    Debug.log('重新加载宿舍楼详情:', buildingId);
                    await this.showBuildingDetails(buildingId);
                    // 如果是从房间记录页面添加的，重新显示房间记录
                    if (modal) {
                        await this.showRecords(roomId);
                    }
                } else {
                    Debug.log('重新加载宿舍楼列表');
                    await this.loadBuildingSelect();
                }
                
                e.target.reset();
            } catch (error) {
                Debug.error('添加卫生检查记录失败:', error);
                alert('添加卫生检查记录失败: ' + error.message);
            } finally {
                loading.hide();
            }
        });
    }
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    HygieneManager.init();
}); 